package org.spring.springboot.controller;

import org.spring.springboot.domain.AdminMenu;
import org.spring.springboot.service.MenuService;
import org.spring.springboot.util.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

/**
 * 描述：菜单Controller
 * <p>
 * Author: 赵新国
 * Date: 2017/10/12 17:51
 */
@RestController
@RequestMapping("/admin")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 用户授权页面
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/userMenuForm")
    public ModelAndView userMenuForm(@RequestParam Short userId) {
        ModelAndView mav = new ModelAndView("/admin/system/userMenuForm");
        List<AdminMenu> menuList = menuService.selectAllMenu(null);
        mav.addObject("menuList", menuList);
        mav.addObject("userId", userId);
        return mav;
    }

    /**
     * 获取所有菜单
     *
     * @return
     */
    @GetMapping(value = "getAllMenuList")
    public List<AdminMenu> getAllMenuList() {
        return menuService.selectAllMenu(null);
    }

    /**
     * 后台菜单管理
     *
     * @return
     */
    @RequestMapping(value = "/menu")
    public ModelAndView menu() {
        return new ModelAndView("admin/system/menu");
    }

    /**
     * 菜单修改页面
     *
     * @param menuId
     * @return
     */
    @GetMapping(value = "/menuForm")
    public ModelAndView menuForm(@RequestParam(required = false) Short menuId) {
        ModelAndView mav = new ModelAndView("/admin/system/menuForm");
        AdminMenu menu = new AdminMenu();
        if (menuId != null) {
            menu = menuService.findAdminMenu(menuId);
        }
        mav.addObject("pMenuList", menuService.selectAllMenu((short) 0));
        mav.addObject("menu", menu);
        return mav;
    }

    /**
     * 保存菜单
     *
     * @param adminMenu
     * @return
     */
    @PostMapping(value = "saveMenu")
    public HashMap<String, Object> saveMenu(@ModelAttribute AdminMenu adminMenu) {
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            menuService.saveMenu(adminMenu);
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 删除菜单
     *
     * @param menuId
     * @return
     */
    @PostMapping(value = "deleteMenu")
    public HashMap<String, Object> deleteMenu(@RequestParam Short menuId) {
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            menuService.deleteMenu(menuId);
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

}
